Page({
  data: {
    isRecording: false,
    recognitionResult: '',
    engineType: '16k_zh',
    voiceFormat: 'wav',
  },

  onLoad() {
    this.recorderManager = wx.getRecorderManager();
    this.recorderManager.onStop((res) => {
      this.setData({ isRecording: false });
      this.uploadAudio(res.tempFilePath); // 传递临时文件路径
    });
  },

  startRecognition() {
    this.setData({ isRecording: true });
    this.recorderManager.start({ format: 'wav' });
  },

  stopRecognition() {
    this.recorderManager.stop();
  },

  async uploadAudio(tempFilePath) {
    try {
      // 实际项目中应上传到COS
      // const publicUrl = await this.uploadToCOS(tempFilePath);
      
      // 测试阶段使用腾讯云公开测试音频
      const publicUrl = 'https://asr-audio-1256237915.cos.ap-shanghai.myqcloud.com/test.wav';
      
      console.log("调用ASR接口，URL:", publicUrl);
      const result = await this.callASRAPI(publicUrl);
      this.setData({ recognitionResult: result });
      
    } catch (error) {
      console.error('语音识别失败:', error);
      wx.showToast({ title: `识别失败: ${error.message}`, icon: 'none' });
    }
  },

  // 上传到COS的实现（需要配置腾讯云API）
  async uploadToCOS(tempFilePath) {
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: 'https://gw.alipayobjects.com/os/bmw-prod/0574ee2e-f494-45a5-820f-63aee583045a.wav', // 替换为你的上传API
        filePath: tempFilePath,
        name: 'file',
        success: (res) => {
          const data = JSON.parse(res.data);
          resolve(data.publicUrl);
        },
        fail: (err) => reject(err)
      });
    });
  },

  // ASR接口调用保持不变
  async callASRAPI(audioUrl) {
    const requestData = {
      Action: "SentenceRecognitionWX",
      EngSerViceType: this.data.engineType,
      VoiceFormat: this.data.voiceFormat,
      UsrAudioKey: Date.now().toString(),
      Url: encodeURIComponent(audioUrl),
      FilterDirty: 2,
      FilterModal: 1,
      ConvertNumMode: 1
    };

    try {
      const response = await wx.request({
        url: "https://asr.tencentcloudapi.com",
        method: "POST",
        header: {
          "Content-Type": "application/json",
          "X-WX-SERVICE-ID": "wxa8386175898e12c9",
          "X-TC-Timestamp": Math.floor(Date.now() / 1000).toString()
        },
        data: JSON.stringify(requestData)
      });

      console.log("API响应:", response.data);
      
      if (!response.data || !response.data.Response) {
        throw new Error(`API响应格式错误: ${JSON.stringify(response.data)}`);
      }

      if (response.data.Response.Error) {
        throw new Error(`API错误: ${response.data.Response.Error.Message}`);
      }

      return response.data.Response.Result;
    } catch (error) {
      console.error("API调用失败", error);
      throw error;
    }
  }
});